package com.lw.sbdemo2.web;

import com.lw.sbdemo2.common.base.BaseController;
import com.lw.sbdemo2.common.constant.TkConstants;
import com.lw.sbdemo2.common.utils.DateUtils;
import com.lw.sbdemo2.common.utils.ValidUtil;
import com.lw.sbdemo2.common.vo.PageInfo;
import com.lw.sbdemo2.common.web.anno.Required;
import com.lw.sbdemo2.common.web.anno.ResultController;
import com.lw.sbdemo2.entity.TkUserAnswerExamRecord;
import com.lw.sbdemo2.entity.TkUserErrorExamDetail;
import com.lw.sbdemo2.entity.TkUserInfo;
import com.lw.sbdemo2.mapper.TkUserAnswerExamRecordMapper;
import com.lw.sbdemo2.mapper.TkUserInfoMapper;
import com.lw.sbdemo2.service.TkUserAnswerExamRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>标题: 用户试卷记录表服务 - 请求控制层</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2019</p>
 * <p>公司: 山人行工作室</p>
 *
 * @version: 1.0
 * @author: LinWang
 * @date 2019-4-14
 */
@ResultController
@Api(description = "TkUserAnswerExamRecordController", tags = {"用户试卷记录表服务"})
@RequestMapping(value = "/tkUserAnswerExamRecord")
public class TkUserAnswerExamRecordController extends BaseController {

    /**
     * 用户试卷记录表服务
     */
    @Autowired
    private TkUserAnswerExamRecordService tkUserAnswerExamRecordService;

    @Autowired
    private TkUserAnswerExamRecordMapper tkUserAnswerExamRecordMapper;

    @Autowired
    private TkUserInfoMapper tkUserInfoMapper;

    @ApiOperation(value = "获取用户试卷记录表列表")
    @GetMapping("")
    public List<TkUserAnswerExamRecord> findList(TkUserAnswerExamRecord tkUserAnswerExamRecord) {
        List<TkUserAnswerExamRecord> resultNew = tkUserAnswerExamRecordService.findList(tkUserAnswerExamRecord);
        List<TkUserAnswerExamRecord> resultArr;
        resultArr = CollectionUtils.isEmpty(resultNew) ? null: resultNew.stream().map(item ->{
            String examType = item.getExamType();
            if (Objects.equals(examType ,TkConstants.EXAM_TYPE_STUDY)) {
                String useTime = item.getUseTime();
                String temp = "";
                if (ValidUtil.isNotEmptyAndNull(useTime) && !useTime.contains(":")) {
                    temp = DateUtils.secToTime(Integer.parseInt(useTime));
                }
                item.setUseTime(temp);
            }
            return item;
        }).collect(Collectors.toList());

        return resultArr;
    }


    @ApiOperation(value = "获取用户试卷记录表列表（分页）", response = PageInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "query", value = "关键词", dataType = "string"),
            @ApiImplicitParam(name = "pageNum", value = "当前页码", required = true, dataType = "int"),
    })
    @GetMapping(value = "/page")
    public PageInfo<TkUserAnswerExamRecord> page(String query, @Required("pageNum") PageInfo pageInfo, TkUserAnswerExamRecord tkUserAnswerExamRecord) {
        return tkUserAnswerExamRecordService.findListPage(query, pageInfo, tkUserAnswerExamRecord);
    }

    @ApiOperation(value = "获取用户答题排名", response = PageInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "query", value = "关键词", dataType = "string"),
            @ApiImplicitParam(name = "pageNum", value = "当前页码", required = true, dataType = "int"),
    })
    @GetMapping(value = "/getRankList")
    public List<TkUserAnswerExamRecord> getRankList(TkUserAnswerExamRecord tkUserAnswerExamRecord) {
        return tkUserAnswerExamRecordService.getRankList(tkUserAnswerExamRecord);
    }

    @ApiOperation(value = "获取教师下答题排名", response = PageInfo.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "query", value = "关键词", dataType = "string"),
        @ApiImplicitParam(name = "pageNum", value = "当前页码", required = true, dataType = "int"),
    })
    @GetMapping(value = "/getTeacherRank")
    public List<TkUserAnswerExamRecord> getTeacherRank(TkUserAnswerExamRecord tkUserAnswerExamRecord) {
        return tkUserAnswerExamRecordService.getTeacherRank(tkUserAnswerExamRecord);
    }

    @ApiOperation(value = "获取班级答题排名", response = PageInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "query", value = "关键词", dataType = "string"),
            @ApiImplicitParam(name = "pageNum", value = "当前页码", required = true, dataType = "int"),
    })
    @GetMapping(value = "/getGradeRank")
    public List<TkUserAnswerExamRecord> getGradeRank(TkUserAnswerExamRecord tkUserAnswerExamRecord) {
        return tkUserAnswerExamRecordService.getGradeRank(tkUserAnswerExamRecord);
    }

    @ApiOperation(value = "导出选中的学生答题成绩", response = PageInfo.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "query", value = "关键词", dataType = "string"),
        @ApiImplicitParam(name = "pageNum", value = "当前页码", required = true, dataType = "int"),
    })
    @GetMapping(value = "/exportUserAnswer")
    public String exportUserAnswer(TkUserAnswerExamRecord tkUserAnswerExamRecord, HttpServletResponse response) throws Exception {
        return tkUserAnswerExamRecordService.exportUserAnswer(tkUserAnswerExamRecord, response);
    }

    @ApiOperation(value = "获取用户试卷记录表详细信息", notes = "根据url的id来获取用户试卷记录表详细信息")
    @ApiImplicitParam(name = "id", value = "用户试卷记录表ID", required = true, dataType = "String")
    @GetMapping("/get")
    public TkUserAnswerExamRecord get(TkUserAnswerExamRecord tkUserAnswerExamRecord) throws Exception {
        //用大于方式查出排名
        TkUserAnswerExamRecord tkUserAnswerExamRecordDb = tkUserAnswerExamRecordService.get(tkUserAnswerExamRecord);
        BigDecimal youScore = tkUserAnswerExamRecordDb.getAnswerScore();
        TkUserInfo tkUserInfo = tkUserInfoMapper.getById(tkUserAnswerExamRecordDb.getUserId());
        String stationRanking = "";
        // 修改之前分数为0的情况，造成答题准确的情况youScore.compareTo(BigDecimal.ZERO) == 0
        if (youScore == null ) {
            //如果分数为空的话，计算准确率排名
            BigDecimal exactRate = tkUserAnswerExamRecordDb.getFirstExactRate();
            if (exactRate == null) {
                stationRanking = "第1名";
            } else {
                Long rank = tkUserAnswerExamRecordMapper.getUserRateRank(tkUserAnswerExamRecord.getExamId(),
                    tkUserAnswerExamRecordDb.getFirstExactRate(),tkUserInfo.getTeacherId());
                stationRanking = "第" + (rank + 1) + "名";
            }
        } else {
            Long rank = tkUserAnswerExamRecordMapper.getUserRank(tkUserAnswerExamRecord.getExamId(),
                tkUserAnswerExamRecordDb.getAnswerScore() ,tkUserInfo.getTeacherId());
            stationRanking = "第" + (rank + 1) + "名";
        }
        tkUserAnswerExamRecordDb.setStationRanking(stationRanking);
        return tkUserAnswerExamRecordDb;
    }

    @ApiOperation(value = "创建用户试卷记录表")
    @PostMapping("/insert")
    public String insert(TkUserAnswerExamRecord tkUserAnswerExamRecord) {

        TkUserAnswerExamRecord tkUserAnswerExamRecordDb = tkUserAnswerExamRecordService.get(tkUserAnswerExamRecord);

        String nowIndex = "";

        if (TkConstants.EXAM_TYPE_STUDY.equals(tkUserAnswerExamRecord.getExamType())) {
            //学习答题，有存在的话直接更新，要从上次记录开始答题
            if (tkUserAnswerExamRecordDb != null) {
                tkUserAnswerExamRecord.setStartTime(new Date());
                tkUserAnswerExamRecordService.update(tkUserAnswerExamRecord);
                nowIndex = tkUserAnswerExamRecordDb.getNowIndex();
            } else {
                tkUserAnswerExamRecord.setStartTime(new Date());
                tkUserAnswerExamRecordService.insert(tkUserAnswerExamRecord);
            }
        } else {
            //已存在，容错，先删除，重复考外面已经控制了
            if (tkUserAnswerExamRecordDb != null) {
                tkUserAnswerExamRecordService.delete(tkUserAnswerExamRecord);
            }
            tkUserAnswerExamRecord.setStartTime(new Date());
            tkUserAnswerExamRecordService.insert(tkUserAnswerExamRecord);
        }

        return nowIndex;
    }

    @ApiOperation(value = "更新用户试卷记录表详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户试卷记录表ID", required = true, paramType = "query", dataType = "String")
    })
    @PostMapping("/update")
    public void update(TkUserAnswerExamRecord tkUserAnswerExamRecord) {
        tkUserAnswerExamRecordService.update(tkUserAnswerExamRecord);
    }

    @ApiOperation(value = "删除用户试卷记录表", notes = "删除用户试卷记录表")
    @ApiImplicitParam(name = "id", value = "用户试卷记录表ID", required = true, paramType = "query", dataType = "String")
    @PostMapping("/delete")
    public void deleteTkUserAnswerExamRecord(TkUserAnswerExamRecord tkUserAnswerExamRecord) {
        tkUserAnswerExamRecordService.delete(tkUserAnswerExamRecord);
    }

}
